<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { logAPI } from '@/services/api'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import ExperimentSelector from '@/components/ExperimentSelector.vue'
import { useExperimentStore } from '@/stores/experiment'

const loading = ref(false)
const experimentParams = ref(null)
const images = ref([])
const imagePath = ref('')

const experimentStore = useExperimentStore()
const selectedExperiment = ref(null)

// 监听实验选择变化
watch(() => selectedExperiment.value, (newVal) => {
  if (newVal) {
    fetchExperimentParams(newVal)
  }
})

// 格式化时间戳
const formatTime = (timestamp) => {
  return dayjs.unix(timestamp).format('YYYY-MM-DD HH:mm:ss')
}

// 过滤掉参数设置时间，因为已经在基本信息中显示
const filteredParameters = computed(() => {
  if (!experimentParams.value?.experiment_parameters) return {}
  const { 参数设置时间, ...rest } = experimentParams.value.experiment_parameters
  return rest
})

// 获取图片URL
const getImageUrl = (imageName, path) => {
  const baseUrl = import.meta.env.VITE_IMAGE_BASE_URL
  return `${baseUrl}/${path.split('/')[1]}/${imageName}`
}

// 获取实验图片
const fetchExperimentImages = async (experimentId) => {
  try {
    const response = await logAPI.getImages({ experimentId })
    images.value = response.data.images || []
    imagePath.value = response.data.path
    
  } catch (error) {
    console.error('Error fetching experiment images:', error)
    ElMessage.error('获取实验图片失败')
  }
}

const fetchExperimentParams = async (experimentId) => {
  loading.value = true
  try {
    const response = await logAPI.getParameters({ experimentId })
    experimentParams.value = response.data
    experimentStore.setCurrentExperiment(experimentId)
    if (experimentId) {
      await fetchExperimentImages(experimentId)
    }
  } catch (error) {
    console.error('Error fetching experiment parameters:', error)
    ElMessage.error('获取实验参数失败')
  } finally {
    loading.value = false
  }
}

// 根据屏幕宽度计算列数
const calculateColumns = () => {
  const width = window.innerWidth - 40
  if (width < 768) return 2 
  if (width < 1600) return 3
  return 4
}

const protectionColumns = ref(calculateColumns())

// 监听窗口大小变化
const handleResize = () => {
  protectionColumns.value = calculateColumns()
}


onMounted(() => {
  fetchExperimentParams('')
  window.addEventListener('resize', handleResize)
})

// 添加预览图片列表
const previewList = computed(() => 
  images.value.map(image => getImageUrl(image, imagePath.value))
)

</script>

<template>
  <div class="log-view" v-loading="loading">
    <!-- 实验ID -->
    <el-card v-if="experimentParams?.experiment_id">
      <template #header>
        <div class="card-header">
          <ExperimentSelector v-model="selectedExperiment" />
        </div>
      </template>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="实验ID">
          {{ experimentParams.experiment_id }}
        </el-descriptions-item>
        <el-descriptions-item label="参数设置时间" v-if="experimentParams.experiment_parameters?.参数设置时间">
          {{ formatTime(experimentParams.experiment_parameters.参数设置时间) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 实验参数 -->
    <el-card v-if="experimentParams?.experiment_parameters" class="mt-4">
      <template #header>
        <div class="card-header">
          <span>实验参数</span>
        </div>
      </template>
      <el-descriptions :column="3" border>
        <el-descriptions-item 
          v-for="(value, key) in filteredParameters" 
          :key="key" 
          :label="key"
        >
          {{ value }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 通道保护阈值 -->
    <el-card v-if="experimentParams?.channel_protections" class="mt-4">
      <template #header>
        <div class="card-header">
          <span>通道保护阈值</span>
        </div>
      </template>
      <el-descriptions :column="protectionColumns" border>
        <template v-for="protection in experimentParams.channel_protections" :key="protection.channel_name">
          <el-descriptions-item :label="protection.channel_name">
            {{ protection.channel_protection_threshold ?? '-' }}
          </el-descriptions-item>
        </template>
      </el-descriptions>
    </el-card>

    <!-- 实验图片 -->
    <el-card v-if="images.length" class="mt-4">
      <template #header>
        <div class="card-header">
          <span>实验图片</span>
        </div>
      </template>
      <div class="image-grid">
        <div 
          v-for="(image, index) in images" 
          :key="image"
          class="image-item"
        >
          <el-image 
            :src="getImageUrl(image, imagePath)"
            :preview-src-list="previewList"
            :initial-index="index"
            fit="cover"
            :alt="image"
            class="preview-image"
          >
            <template #error>
              <div class="image-error">
                <el-icon><picture-filled /></el-icon>
                <span>加载失败</span>
              </div>
            </template>
          </el-image>
          <div class="image-name">{{ image }}</div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.log-view {
  padding: 20px;
}

.mt-4 {
  margin-top: 16px;
}

.card-header {
  font-weight: bold;
}

:deep(.el-descriptions__cell) {
  min-width: 200px;  /* 设置最小宽度 */
}

:deep(.el-descriptions__label) {
  width: 150px;
  justify-content: flex-end;
  color: #606266;
  font-weight: bold;
}

:deep(.el-descriptions__content) {
  justify-content: center;  /* 数值居中显示 */
}

</style>